<?php
/**
 * 绵阳妇幼中间件
 *
 *
 * @author wangwh
 */

namespace Pzhrs\Controller;

class PzhApiController
{
    // SoapClient 对象
    private $soap = FALSE;

    // 记录是否为正式环境
    private $isFormal = FALSE;

    //是否开启缓存
    private static $CACHE = false;

    // 医疗机构科室列表缓存建
    private static $CACHE_INSTITUTION_CLASS_LIST = 'CACHE_INSTITUTION_CLASS_LIST';


    static $URL_API = 'http://220.166.60.252:8083/wxjk.dll/wsdl/Iwxjk';//http://192.168.203.55:8078/HisService.asmx?WSDL
    static $back_URL_API = "http://localhost:8081/";

    //医院id
    private $hospitalId;

    //自助机id
    private $userId;

    /**
     * 构造函数
     */
    function __construct()
    {
        header('Content-Type: text/html; charset=utf-8');
        $this->hospitalId = 75;
        if (!method_exists($this, ACTION_NAME)) {
            $function = ACTION_NAME;
            A('Receive')->$function();
        }
    }

    public function xml_to_array($list){
        $ob= simplexml_load_string($list);
        $json  = json_encode($ob);
        $configData = json_decode($json, true);
        return $configData;
    }

    public $hospitalKey = array(
        "75" => "7daf7603429012aeae417fa9beed9c75",
    );
    //正式地址
    //	static $URL_API = "http://125.64.9.81:8088/rmc/mobile/web";
    //	static $version = "2.2.7";
    //	private $token = "6a2967e64a994e54b533aa7942328179";
    //正式地址


    // 	static $URL_API = "http://125.64.9.81:8088/rmc/mobile/web";
    /**
     * 请求His API
     *
     *   使用SoapClient请求HIS webservice接口
     *
     * @param String $Flag 类型
     * @param String $Content xml请求内容
     * @param String $Result_K 返回xml中的跟节点key
     *
     * @return array
     */


    private function soapGetDate($Flag, $Content)
    {
//        $this->isFormal = ($_SERVER['SERVER_NAME']!="localhost" && "histest.mobimedical.cn"!=$_SERVER['SERVER_NAME']);
        $this->isFormal = false;

        if (!$this->soap) {
            $this->soap = new \SoapClient(self::$URL_API, array("connection_timeout" => 15));
        }
        try {

            /* 正式环境 */
            if ($this->isFormal) {
                //专线接口,走平台
                try {
                    $result = $this->soap->Weixin($Content);
                } catch (\Exception $e) {
                    $fileContent = $Content . "\n" . $e->getMessage();
                    $dir = "soapGetDate/";
                    \Org\Util\File::createDir($dir);
                    file_put_contents($dir . $Flag . "_error.txt", $fileContent);
                    return array('ResultCode' => -1, "ErrorMsg" => "系统异常，请稍后重试21！");
                }
                $Result_K = "Weixin" . Result;

                /* 测试环境 */
            } else {
                $result = $this->soap->$Flag( $Content);
                /* 记录请求日志   */
                $fileContent = $Content . "\r" . var_export($result, true);
                $dir = "soapGetDate/" . date("Y-m-d") . "/" . $Flag . "/";
                $filename = date("H_i_s") . "_" . rand(10000, 99999);
                writeLog($dir, $filename, $fileContent);

                return json_decode(json_encode(json_decode(json_encode((array)simplexml_load_string(substr($result, 54)), true))), true);
            }


        } catch (\Exception $e) {
            /* 记录请求异常日志  */
            $fileContent = $Content . "\n" . $e->getMessage();
            $dir = "soapGetDate/" . date("Y-m-d") . "/" . $Flag . "/";
            $filename = date("H_i_s") . "_error";
            writeLog($dir, $filename, $fileContent);
            return array('ResultCode' => -1, "ErrorMsg" => "系统异常，请稍后重试22！");
            exit;
        }
    }


    function Post($url, $method, $post = null)
    {
        if (is_array($post)) {
            ksort($post);
            $content = http_build_query($post);
            $content_length = strlen($content);
            $options = array(
                'http' => array(
                    'method' => 'POST',
                    'header' =>
                        "Content-type: application/x-www-form-urlencoded; charset=utf-8\r\n" .
                        "Content-length: $content_length\r\n",
                    'content' => $content
                )
            );
            $res = file_get_contents($url, false, stream_context_create($options));
            $fileContent = var_export($post, true) . "\r" . var_export($res, true) . "\r" . var_export(json_decode($res, true), true);
            $dir = "soapGetDateXt/" . date("Y-m-d") . "/" . $method . "/";
            $filename = date("H_i_s") . "_" . rand(10000, 99999);
            writeLog($dir, $filename, $fileContent);
            return $res;
        }
    }

    /**
     * 中间件签名验证
     * @param array $params
     * @return string
     */
    function middelEnCodeSign($params)
    {
        ksort($params);
        $preString = "";
        $time = $params['time'];
        $hospitalId = $params['hospitalId'];
        foreach ($params as $k => $v) {
            if ($k == 'time' || $k == 'sign' || !$v)
                continue;
            $preString .= $k . "=" . $v;
        }

        $keyString = $this->hospitalKey[$hospitalId];
        //加密
        return sha1($preString . $keyString . $time);
    }



    /**
     * 统一调接口方法
     * $xml       接口传递的参数
     * $funNo     接口的方法名
     * $client    接口需要调用的webservice对象
     * */
	function Get_service_api($xml,$funNo,$client){
        $mmkj='http://yinhai.com';
        $code='wx20170921'; //授权码
        //$apiUrl='http://pzh.91cure.com/index.php?g=Home&m=Test&a=pzh_sign';
        //$apiUrl='http://127.0.0.1:442/index.php?g=Whszxyy&m=WhszxyyControlxin1&a=pzh_sign';
        //$params1 = array();
        //$params1['content']=$xml;
        //$xmlsing=$this->PostData_jm($apiUrl,$params1);

        $content = htmlspecialchars_decode($xml);
        $priKey = file_get_contents($rsaPrivateKeyPem);
        //echo $content;
        $priKey='-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQCQq3qatgsHLl4E2OKsMDYS07yp+Vdxxq6oHgdp5DmzXlt28b/u
/ezex7kNrNHWVcycaLqeX43Xp4ByO6ELjVbfP2XNhXN7pOMh5KNLbUvGP5YultKl
AMRk25HN9rjp8RHZHlS0qpR5Y5sitK3AR19VlAPKUaoslBlCaAPqGwsQkwIDAQAB
AoGARzt30eeixHVrK73S1m+ioGCLO7IfAVGPvA2VHumWE6B5LrbYB4gV8peqoXYf
mAaFCdpzUPnBsJa0IwsDP9nnFJ6EwYfvFtgihipWgx3HZ0tyLu6gNW9ORFP9RCtE
u05J8JbjYOcJP3Pwu3RQ715yoxbmAe2SzwHiXrJSUgVSsQkCQQD+YpPlkxLrGbxI
nbNAZQRO4udJIUmBt0uTNiJ8TEZ9h45aeLRYgtBy28YMBgCkBJACFuJ7MufPvwQC
4lPHJKT/AkEAkZaYCIs1A778bDvxIyGhTcUmNxTti2HEFbUFfkXXDKaxu53uxNCw
roztQD3rtGEhSGQKoO8ax0bjyIDzaX8wbQJAGsJn6Gh2PwDwC3t7VbTKpTm9NrYn
s1uCubOiIQ0tBRtzYBT+c6kfIFX6GV2wR5CrTWz22hraw8HGPD9urK4wJQJAA+V9
6CyhnJoN82+fQotx37z5CtxahzJ0pwgTP4/q84G6nATcERRsxh8rcl614jv/Qgq7
ZhdAJjk1e3ZIDXjD+QJAIF07entOK7DhmHKOXJPtgMaVdXd1QUER1NuDpQTBKTim
hjs4JBVWvXgUwPH1lZaiSoJnHrL/G3Sw3K/DJEEdKw==
-----END RSA PRIVATE KEY-----';
        $res = openssl_pkey_get_private($priKey);
        openssl_sign($content, $sign, $res);
        openssl_free_key($res);
        //$sign = base64_encode($sign);
        $xmlsing = bin2hex($sign);

        $auth_header = array( "jybh" =>$funNo ,"systemKey" =>$code ,"source" =>$xml,"signature" =>$xmlsing  );
        $authvalues = new \SoapVar($auth_header, SOAP_ENC_OBJECT,"system",$mmkj);
        $u = new \SoapHeader($mmkj, 'system', $authvalues);
        $client->__setSoapHeaders($u);
        $params['inputxml']=$xml;
        $suc=$client->callBusiness($params);
        $data=$suc->return;
		if ($funNo == 'HMHN001') {
            $data = str_replace('<?xml version="1.0" encoding="GBK"?>', '', $data);
        }
        $tesres = $this->xml_to_array($data);
		if (isset($tesres['code']) && $tesres['code'] == 'NOERROR') {
            $tesres['code'] = "1";
        }
        return  $tesres;
    }

    // function Get_service_api($xml,$funNo,$client){
        // $mmkj='http://yinhai.com';
        // $code='wx20170921'; //授权码
        // $apiUrl='http://pzh.91cure.com/index.php?g=Home&m=Test&a=pzh_sign';
        // $params1 = array();
        // $params1['content']=$xml;
        // $xmlsing=$this->PostData_jm($apiUrl,$params1);
        // //echo strlen($xmlsing);
        // //echo "<br>";
        // //echo strlen($xmlsing1);
        // //echo "<br>";
        // //dump($xmlsing1);die();
        // $auth_header = array( "jybh" =>$funNo ,"systemKey" =>$code ,"source" =>$xml,"signature" =>$xmlsing  );
        // $authvalues = new \SoapVar($auth_header, SOAP_ENC_OBJECT,"system",$mmkj);
        // $u = new \SoapHeader($mmkj, 'system', $authvalues);
        // $client->__setSoapHeaders($u);
        // $params['inputxml']=$xml;
        // $suc=$client->callBusiness($params);
        // $data=$suc->return;
        // $tesres = $this->xml_to_array($data);
        // return  $tesres;
    // }
    /**
     * 数字签名
     * $url         签名地址
     * $post        签名参数
     * */
    function PostData_jm($url, $post = null) {
        if (is_array($post)) {
            ksort($post);
            $content = http_build_query($post);
            $content_length = strlen($content);
            $options = array(
                'http' => array(
                    'method' => 'POST',
                    'header' =>
                    "Content-type: application/x-www-form-urlencoded\r\n"."Content-length: $content_length\r\n",
                    'content' => $content
                )
            );
            $now = time();
            $res = file_get_contents($url, false, stream_context_create($options));
            return substr(urlencode($res),9);//
            //return $res;
        }
    }


	/**
     * 养老保险缴费信息查询TEST
     * @param
     */
    function GetPensionPayment_InquireTEST(){
        $tcylkey = C('TCYL_KEY');
        //$wx_openid  = $tcylkey.$_POST['wx_openid'];
        $wx_openid='tcyl_ohNH9sgZMMsP6MFSG5mrbrQXnYk4'; //第三方ID
        $funNo='WX_001';    //交易编号
        $xml="<input><inputxml><inputxml><yad901>".$wx_openid."</yad901></inputxml></inputxml></input>";
        //dump($xml);
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);
        echo json_encode($result_list);
    }

    /**
     * 医疗保险缴费信息查询
     * @param
     */
    function GetMedicalInsurance_Inquire(){
        $tcylkey = C('TCYL_KEY');
        $wx_openid  = $tcylkey.$_POST['wx_openid'];
        //$wx_openid='tcyl_oeTsDv8zEhse5Hs_isEog1ncAlQ8'; //第三方ID
        $funNo='WX_003';    //交易编号
        $xml="<input><inputxml><inputxml><yad901>".$wx_openid."</yad901></inputxml></inputxml></input>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

		$fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/WX_003/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        echo json_encode($result_list);
    }

    /**
     * 职工医疗保险缴费信息查询
     * @param
     */
    function GetMedicalInsuranceZG_Inquire(){
        $tcylkey = C('TCYL_KEY');
        $wx_openid  = $tcylkey.$_POST['wx_openid'];
        //$wx_openid='tcyl_oeTsDv8zEhse5Hs_isEog1ncAlQ8'; //第三方ID
        $funNo='WX_003_ZG';    //交易编号
        $xml="<input><inputxml><inputxml><yad901>".$wx_openid."</yad901></inputxml></inputxml></input>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

		$fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/WX_003_ZG/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        echo json_encode($result_list);
    }

    /**
     * 居民医疗保险缴费信息查询
     * @param
     */
    function GetMedicalInsuranceJM_Inquire(){
        $tcylkey = C('TCYL_KEY');
        $wx_openid  = $tcylkey.$_POST['wx_openid'];
        //$wx_openid='tcyl_oeTsDv8zEhse5Hs_isEog1ncAlQ8'; //第三方ID
        $funNo='WX_003_JM';    //交易编号
        $xml="<input><inputxml><inputxml><yad901>".$wx_openid."</yad901></inputxml></inputxml></input>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

		$fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/WX_003_JM/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        echo json_encode($result_list);
    }

    /**
     * 生育保险缴费信息查询
     * @param
     */
    function GetMaternityInsurance_Inquire(){
        $tcylkey = C('TCYL_KEY');
        $wx_openid  = $tcylkey.$_POST['wx_openid'];
        //$wx_openid='tcyl_oeTsDv8zEhse5Hs_isEog1ncAlQ8'; //第三方ID
        $funNo='WX_005';    //交易编号
        $xml="<input><inputxml><inputxml><yad901>".$wx_openid."</yad901></inputxml></inputxml></input>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

		$fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/WX_005/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        echo json_encode($result_list);
    }

    /**
     * 制卡查询
     * @param
     */
    function GetCard_Inquiries(){
        $tcylkey = C('TCYL_KEY');
        //$wx_openid='tcyl_oeTsDv8zEhse5Hs_isEog1ncAlQ8'; //第三方ID
        //$identyId='510402198306076317';    //社会保障号(身份证号码)
        //$name='张帆';     //姓名

        $wx_openid = $tcylkey.$_POST['wx_openid'];
        $identyId = $_POST['identyId'];
        $name = $_POST['name'];
        $funNo='WZ2000';    //交易编号
        $xml="<input><inputxml><inputxml><yad901>".$wx_openid."</yad901><aac002>".$identyId."</aac002><aac003>".$name."</aac003><fwid>".$funNo."</fwid></inputxml></inputxml></input>";
        /* 记录请求日志   */
            $fileContent = var_export($xml, true);
            $dir = "soapGetDate/" . date("Y-m-d") . "/GetCard_Inquiries_rc/";
            $filename = date("H_i_s") . "_" . rand(10000, 99999);
            writeLog($dir, $filename, $fileContent);
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);
        /* 记录请求日志   */
            $fileContent = var_export($result_list, true);
            $dir = "soapGetDate/" . date("Y-m-d") . "/GetCard_Inquiries_Re/";
            $filename = date("H_i_s") . "_" . rand(10000, 99999);
            writeLog($dir, $filename, $fileContent);
        echo json_encode($result_list);
    }


     /**
     * 职工医保个人账户收支查询
     * @param
     */
    function GetPersonalIncome_Expenditure(){
        $tcylkey = C('TCYL_KEY');
        //$wx_openid  = 'tcyl_oeTsDvx_c9sJhQ3XrqxBeVsfDJxY';
        //$IncomeExpenditure_Type = '1';    //收支类型  1收入,2支出
        //$StartData = '1';  //开始行
        //$EndData = '10';    //结束行

        $wx_openid = $tcylkey.$_POST['wx_openid'];
        $IncomeExpenditure_Type = $_POST['IncomeExpenditure_Type'];
        $StartData = $_POST['StartData'];
        $EndData = $_POST['EndData'];
        $funNo='WX_015';    //交易编号
        $xml="<input><inputxml><inputxml><yad901>".$wx_openid."</yad901><yad904>".$IncomeExpenditure_Type."</yad904><aae030>".$StartData."</aae030><aae031>".$EndData."</aae031></inputxml></inputxml></input>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

		$fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/WX_015/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

		if (isset($result_list['output']['row'])) {
            if (isset($result_list['output']['row']['aae013'])) {
                if ($result_list['output']['row']['aae013'] == 'null') {
                    $result_list['output']['row']['aae013'] = '';
                }
                if ($result_list['output']['row']['akb021'] == 'null') {
                    $result_list['output']['row']['akb021'] = '';
                }
            }
            foreach ($result_list['output']['row'] as $k => &$v) {
                if ($v['aae013'] == 'null') {
                    $v['aae013'] = '';
                }
                if ($v['akb021'] == 'null') {
                    $v['akb021'] = '';
                }
            }
        }

        echo json_encode($result_list);
    }

	/**
     * 机关养老缴费明细
     * @param
     */
    function CKKQ017(){
        $tcylkey = C('TCYL_KEY');
        $wx_openid = $tcylkey.$_POST['wx_openid'];
        $WX017Res = $this->WX017($wx_openid);
        if ($WX017Res['code'] == 0) {
            echo json_encode($WX017Res);exit;
        }
        $cardNo = $WX017Res['message'];
        //<sid>个人编号</sid> (由CKKQ016获取)
        $CKKQ016Res = $this->CKKQ016($cardNo);
        if ($CKKQ016Res['code'] == 0) {
            echo json_encode($CKKQ016Res);exit;
        }
        $sid = $CKKQ016Res['message'];
        //险种(事业单位基本养老保险(120)、职业年金(180))
        $insuranceType = $_POST['insurance_type'];
        //发放开始期号
        $StartData = $_POST['start_data'];
        //发放终止期号
        $EndData = $_POST['end_data'];
        $funNo='CKKQ017';    //交易编号
        $xml="<inputxml><sid>".$sid."</sid><aae140>".$insuranceType."</aae140><aae041>".$StartData."</aae041><aae042>".$EndData."</aae042></inputxml>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/CKKQ017/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

		if ($result_list['output']['resultset']['row'][0]['aab004']) {
            foreach ($result_list['output']['resultset']['row'] as $k=>&$v){
                $temp[]=$v['dwjfrq'];
            }
            $res = [];
            foreach ($result_list['output']['resultset']['row'] as $k=>&$v){
                if ($v['dwjfrq'] == max($temp)) {
                    $res = $v;
                    break;
                }
            }
            unset($result_list['output']['resultset']['row']);
            $result_list['output']['resultset']['row'] = $res;
        }

        echo json_encode($result_list);
    }

    /**
     * 居民养老待遇信息
     * @param
     */
    function CKKQ011(){
        $tcylkey = C('TCYL_KEY');
        $wx_openid = $tcylkey.$_POST['wx_openid'];
        $WX017Res = $this->WX017($wx_openid);
        if ($WX017Res['code'] == 0) {
            echo json_encode($WX017Res);exit;
        }
        $cardNo = $WX017Res['message'];
        //$cardNo = '510402195103050033';
        $funNo='CKKQ011';    //交易编号
        $xml="<inputxml><aac002>".$cardNo."</aac002><aab034></aab034><aae140>170</aae140></inputxml>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/CKKQ011/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        echo json_encode($result_list);
    }


    /**
     * 机关养老待遇发放明细
     * @param
     */
    function CKKQ018(){
        $tcylkey = C('TCYL_KEY');
        $wx_openid = $tcylkey.$_POST['wx_openid'];
        $WX017Res = $this->WX017($wx_openid);
        if ($WX017Res['code'] == 0) {
            echo json_encode($WX017Res);exit;
        }
        $cardNo = $WX017Res['message'];
        //$cardNo = '510402194901155513';
        //<sid>个人编号</sid> (由CKKQ016获取)
        $CKKQ016Res = $this->CKKQ016($cardNo);
        if ($CKKQ016Res['code'] == 0) {
            echo json_encode($CKKQ016Res);exit;
        }
        $sid = $CKKQ016Res['message'];
        //发放开始期号
        $StartData = $_POST['start_data'];
        //发放终止期号
        $EndData = $_POST['end_data'];
        //开始页数
        $startRow = $_POST['start_row'];
        //结束页数
        $endRow = $_POST['end_row'];
        $endRow = 1;
        $funNo='CKKQ018';    //交易编号
        $xml="<inputxml><sid>".$sid."</sid><aae041>".$StartData."</aae041><aae042>".$EndData."</aae042><startrow>".$startRow."</startrow><endrow>".$endRow."</endrow></inputxml>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/CKKQ018/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

		if ($result_list['output']['resultset']['row'][0]['aae003']) {
            foreach ($result_list['output']['resultset']['row'] as $k=>&$v){
                $temp[]=$v['aae003'];
            }
            $res = [];
            foreach ($result_list['output']['resultset']['row'] as $k=>&$v){
                if ($v['aae003'] == max($temp)) {
                    $res = $v;
                    break;
                }
            }
            unset($result_list['output']['resultset']['row']);
            $result_list['output']['resultset']['row'] = $res;
        }

        echo json_encode($result_list);
    }

    /**
     * 机关养老人员信息(给017,018用不对外开发)
     * @param
     */
    function CKKQ016($cardNo){
        $funNo='CKKQ016';    //交易编号
        $xml="<inputxml><aac002>".$cardNo."</aac002></inputxml>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/CKKQ016/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        $res['code'] = 0;
        if (isset($result_list['output']['resultset']['row'][0]['aac001'])) {
            $res['code'] = 1;
            $res['message'] = $result_list['output']['resultset']['row'][0]['aac001'];
            return $res;
        }
        $res['message'] = $result_list['message'].'CKKQ016';
        return $res;
    }

    /**
     * 查询用户信息
     * @param
     */
    function WX017($wx_openid){
        $funNo='WX_017';    //交易编号
        $xml="<input><inputxml><inputxml><yad901>".$wx_openid."</yad901></inputxml></inputxml></input>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

        $res['code'] = 0;
        if (isset($result_list['output']['aac002'])) {
            $res['code'] = 1;
            $res['message'] = $result_list['output']['aac002'];
            return $res;
        }
        $res['message'] = $result_list['message'].'WX017';
        return $res;
    }

    /**
     * 城乡居民养老缴费信息
     * @param
     */
    function CKKQ007(){
        $tcylkey = C('TCYL_KEY');
        $wx_openid = $tcylkey.$_POST['wx_openid'];
        $WX017Res = $this->WX017($wx_openid);
        if ($WX017Res['code'] == 0) {
            echo json_encode($WX017Res);exit;
        }
        $cardNo = $WX017Res['message'];
        //$cardNo = '510522196906301786';
        //起始缴费年度
        $StartData = $_POST['start_data'];
        //终止缴费年度
        $EndData = $_POST['end_data'];
        //开始页数
        $startRow = $_POST['start_row'];
        //结束页数
        $endRow = $_POST['end_row'];
        $endRow = 1;
        $funNo='CKKQ007';    //交易编号
        $xml="<inputxml><aac001></aac001><aac002>".$cardNo."</aac002><aab034></aab034><aae041>".$StartData."</aae041><aae042>".$EndData."</aae042><aae140>170</aae140><startrow>".$startRow."</startrow><endrow>".$endRow."</endrow></inputxml>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);
        if (isset($result_list['output']['resultset']['row'])) {
            //待遇发放状态
            $payState = [
                'R10' => '正常应缴',
                'R101' => '老系统卡年费',
                'R102' => '老系统当期统筹',
                'R103' => '应缴未缴补收',
                'R105' => '转入',
                'R107' => '异地安置退费',
                'R109' => '村集体补助',
                'R11' => '补缴',
                'R112' => '特殊补助（可继承）',
                'R113' => '特殊补助（不可继承）',
                'R15' => '实缴划拨',
                'R20' => '人员退费',
                'R31' => '中断或延迟年限补收',
                'R32' => '有补贴补缴',
                'R33' => '退休补收',
                'R40' => '一次性缴费',
                'R50' => '待转金核定',
                'R51' => '零星缴款',
                'R52' => '待转金调整',
                'R53' => '待转金分配',
                'R54' => '退款进待转',
                'R561' => '待转账参与基金征集',
                'R562' => '待转账转待转金',
                'R60' => '个人补欠费',
                'R64' => '支款给商业保险公司',
                'R65' => '财政承担核定',
                'R66' => '被征地农民补贴申请',
                'R67' => '居民学校统筹划',
                'R70' => '财务按期缴费',
                'R88' => '退款进统筹',
                'R90' => '转出',
                'R91' => '采集账户推算'
            ];
            if ($result_list['output']['recordcount'] == 1) {
                $result_list['output']['resultset']['row']['aaa115'] = $payState[$result_list['output']['resultset']['row']['aaa115']];
            }else{
                foreach ($result_list['output']['resultset']['row'] as $k => &$v) {
                    $v['aaa115'] = $payState[$v['aaa115']];
                }
            }
			if ($result_list['output']['resultset']['row'][0]['aae042']) {
                foreach ($result_list['output']['resultset']['row'] as $k=>&$v){
                    $temp[]=$v['aae042'];
                }
                $res = [];
                foreach ($result_list['output']['resultset']['row'] as $k=>&$v){
                    if ($v['aae042'] == max($temp)) {
                        $res = $v;
                        break;
                    }
                }
                unset($result_list['output']['resultset']['row']);
                $result_list['output']['resultset']['row'] = $res;
            }

        }

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/CKKQ007/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        echo json_encode($result_list);
    }

    /**
     * 城乡居民养老待遇信息
     * @param
     */
    function CKKQ014(){
        $tcylkey = C('TCYL_KEY');
        $wx_openid = $tcylkey.$_POST['wx_openid'];
        $WX017Res = $this->WX017($wx_openid);
        if ($WX017Res['code'] == 0) {
            echo json_encode($WX017Res);exit;
        }
        $cardNo = $WX017Res['message'];
        //$cardNo = '510402195103050033';
        //发放开始期号
        $StartData = $_POST['start_data'];
        //发放终止期号
        $EndData = $_POST['end_data'];
        $funNo='CKKQ014';    //交易编号
        $xml="<inputxml><aac002>".$cardNo."</aac002><aab034></aab034><aae140>170</aae140><aae041>".$StartData."</aae041><aae042>".$EndData."</aae042></inputxml>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

        if (!isset($result_list['output']['resultset']['row'])) {
            //待遇发放状态
            $sendState = [
                '0' => '业务未支付',
                '1' => '业务已支付',
                '2' => '财务已支付',
                '3' => '在途',
                '4' => '财务支付成功',
                '5' => '财务支付失败',
                '6' => '失败不重发',
                '9' => '部分支付'
            ];
            if ($result_list['output']['recordcount'] == 1) {
                $result_list['output']['resultset']['row']['aae117'] = $sendState[$result_list['output']['resultset']['row']['aae117']];
            }else{
                foreach ($result_list['output']['resultset']['row'] as $k => &$v) {
                    $v['aae117'] = $sendState[$v['aae117']];
                }
            }
            if ($result_list['output']['resultset']['row'][0]['aae002']) {
                foreach ($result_list['output']['resultset']['row'] as $k=>&$v){
                    $temp[]=$v['aae002'];
                }
                $res = [];
                foreach ($result_list['output']['resultset']['row'] as $k=>&$v){
                    if ($v['aae002'] == max($temp)) {
                        $res = $v;
                        break;
                    }
                }
                unset($result_list['output']['resultset']['row']);
                $result_list['output']['resultset']['row'] = $res;
            }
        }

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/CKKQ014/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        echo json_encode($result_list);
    }

	/**
     * 机关养老历年个人账户信息
     * @param
     */
    function CKKQ019(){
        $tcylkey = C('TCYL_KEY');
        $wx_openid = $tcylkey.$_POST['wx_openid'];
        $WX017Res = $this->WX017($wx_openid);
        if ($WX017Res['code'] == 0) {
            echo json_encode($WX017Res);exit;
        }
        $cardNo = $WX017Res['message'];
        //<sid>个人编号</sid> (由CKKQ016获取)
        $CKKQ016Res = $this->CKKQ016($cardNo);
        if ($CKKQ016Res['code'] == 0) {
            echo json_encode($CKKQ016Res);exit;
        }
        $sid = $CKKQ016Res['message'];
        $funNo='CKKQ019';    //交易编号
        $xml="<inputxml><sid>".$sid."</sid><aae140>120</aae140><aae041>1</aae041><aae042>1</aae042><startrow>1</startrow><endrow>100</endrow></inputxml>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/CKKQ019/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

		if (isset($result_list['output']['resultset']['row'])) {
            $array['code'] = "1";
            $array['message'] = "";
            $jfys = 0;
            if (isset($result_list['output']['resultset']['row'][0]['nd'])) {
                foreach ($result_list['output']['resultset']['row'] as $k=>&$v){
                    $temp[]=$v['nd'];
                    $jfys += intval($v['jfys']);
                }
                $res = [];
                foreach ($result_list['output']['resultset']['row'] as $k=>&$v){
                    if ($v['nd'] == max($temp)) {
                        $res = $v;
                        break;
                    }
                }
                unset($result_list['output']['resultset']['row']);
                $result_list['output']['resultset']['row'] = $res;
            }else{
                $jfys = $result_list['output']['resultset']['row']['jfys'];
            }
            $array['output']['resultset']['row'][0]['jfys'] = $jfys;
            $array['output']['resultset']['row'][0]['aae240'] = $result_list['output']['resultset']['row']['aae240'];
            $array['output']['recordcount'] = "1";
            $fileContent = '入参'.$xml.'+出参'.json_encode($array);
            $dir = "soapGetDate/" . date("Y-m-d") . "/CKKQ019s/";
            $filename = date("H_i_s") . "_" . rand(10000, 99999);
            writeLog($dir, $filename, $fileContent);
            echo json_encode($array);die;
        }

        echo json_encode($result_list);
    }

	/**
     * 养老生成认证接口
     * @param
     */
    function pensionToken(){
        $funNo = 'cdsi0001601';    //交易编号
        //身份证号
        $aac002 = $_POST['aac002'];
        //姓名
        $aac003 = $_POST['aac003'];
        //备注(写手机号)
        $aae013 = $_POST['aae013'];

        //个人ID
        $cdsi0000004Res = $this->cdsi0000004($aac002);
        if ($cdsi0000004Res['code'] == 0) {
            echo json_encode($cdsi0000004Res);exit;
        }
        $aac001 = $cdsi0000004Res['message'];

        //业务日志ID
        $aaz002 = time().'000';
        //性别(男1女2)
        $sexint = (int) substr($aac002, 16, 1);
        $aac004 = $sexint % 2 === 0 ? '2' : '1';
        //健康状况(1健康良好2一般或较弱3有慢性病6残疾)
        $aac033 = 1;
        //认证时间
        $aae036 = date('Ymd', time());
        $xml = "<input><aaz002>".$aaz002."</aaz002><aac004>".$aac004."</aac004><aaa135>50</aaa135><aaa094>1</aaa094><bae135>52</bae135><aae036>".$aae036."</aae036><aaa027>510499</aaa027><aae011>19228637</aae011><aae013>".$aae013."</aae013><aac003>".$aac003."</aac003><aac033>".$aac033."</aac033><aac001>".$aac001."</aac001><aac002>".$aac002."</aac002></input>";
        $client = new \SoapClient(C('URL_API'));
        $result_list = $this->Get_service_api($xml, $funNo, $client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/cdsi0001601/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        $res['code'] = 0;
        $res['message'] = '未查询到您的本地企业养老退休待遇信息，请到人社经办机构核实！';
        if ($result_list['code'] == 1) {
            $res['code'] = 1;
            $res['message'] = 'success';
        }
        echo json_encode($res);
    }

    function cdsi0000004($cardNo){
        $funNo='cdsi0000004';    //交易编号
        $xml="<inputxml><aac002>".$cardNo."</aac002></inputxml>";
        $client=new \SoapClient(C('URL_API'));
        $result_list=$this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/cdsi0000004/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        $res['code'] = 0;
        if (isset($result_list['output']['recordcount']) && $result_list['output']['recordcount'] == 1) {
            $res['code'] = 1;
            $res['message'] = $result_list['output']['resultset']['row']['aac001'];
            return $res;
        }
        $res['message'] = '个人编号查询错误';
        return $res;
    }

    /**
     * 获取上次认证时间
     * @param
     */
    function getAuthTime(){
        $cardNo = $_POST['aac002'];

        $funNo = 'cdsi0001026';    //交易编号
        $xml = "<inputxml><aac002>".$cardNo."</aac002></inputxml>";
        $client = new \SoapClient(C('URL_API'));
        $result_list = $this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/cdsi0001026/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        $res['code'] = 0;
        $res['message'] = '认证时间查询错误';
        if (isset($result_list['output']['recordcount']) && $result_list['output']['recordcount'] == "1" && $result_list['output']['resultset']['row']['aac003'][0] != null) {
            $res['code'] = 1;
            $res['message'] = 'success';
            $res['item'] = $result_list['output']['resultset']['row'];
        }
        echo json_encode($res);
    }

	/**
     * 惠民惠农_业务办理情况查询
     */
    function HM0001(){
        //身份证号
        $aac002 = $_POST['user_card_no'];
        //姓名
        $aac003 = $_POST['user_name'];

        $funNo = 'HMHN001';    //交易编号
        $xml = "<input><aac002>".$aac002."</aac002><aac003>".$aac003."</aac003><chw017>01</chw017><fwbh>getYwInfo</fwbh></input>";
        $client = new \SoapClient(C('URL_API'));
        $result_list = $this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/HM0001/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        $res['code'] = 0;
        $res['message'] = '暂未查询到关于您的惠民惠农相关业务办理情况';
        if (isset($result_list['code']) && $result_list['code'] == "1") {
            if (count($result_list['output']) == 0) {
                $res['message'] = '暂未查询到关于您的惠民惠农相关业务办理情况';
                echo json_encode($res);exit();
            }
            $res['code'] = 1;
            $res['message'] = 'success';
            $res['item'] = $result_list['output'];
        }
        echo json_encode($res);
    }

    /**
     * 惠民惠农_业务办理过程详情展示查询
     */
    function HM0002(){
        //业务主键
        $chb010 = $_POST['chb010'];

        $funNo = 'HMHN001';    //交易编号
        $xml = "<input><chb010>".$chb010."</chb010><chw017>01</chw017><fwbh>getBusinessPlan</fwbh></input>";
        $client = new \SoapClient(C('URL_API'));
        $result_list = $this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/HM0002/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        $res['code'] = 0;
        $res['message'] = '暂未查询到关于您的惠民惠农相关业务办理情况';
        if (isset($result_list['code']) && $result_list['code'] == "1") {
            if (count($result_list['output']) == 0) {
                $res['message'] = '暂未查询到关于您的惠民惠农相关业务办理情况';
                echo json_encode($res);exit();
            }
            $res['code'] = 1;
            $res['message'] = 'success';
            $res['item'] = $result_list['output'];
        }
        echo json_encode($res);
    }

    /**
     * 惠民惠农_获取政策文件最新的三个标题查询
     */
    function HM0004(){
        //身份证号
        $number = $_POST['user_card_no'];

        $funNo = 'HMHN001';    //交易编号
        $xml = "<input><number>".$number."</number><chw017>01</chw017><fwbh>getPolicyInfoByNumber</fwbh></input>";
        $client = new \SoapClient(C('URL_API'));
        $result_list = $this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/HM0004/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        $res['code'] = 0;
        $res['message'] = '暂未查询到相关政策文件信息';
        if (isset($result_list['code']) && $result_list['code'] == "1") {
            if (count($result_list['output']) == 0) {
                $res['message'] = '暂未查询到相关政策文件信息';
                echo json_encode($res);exit();
            }
            $res['code'] = 1;
            $res['message'] = 'success';
            $res['item'] = $result_list['output'];
        }
        echo json_encode($res);
    }

    /**
     * 惠民惠农_按条件获取相关政策文件查询
     */
    function HM0005(){
        //业务局码值
        $chi037 = $_POST['chi037'];
        //所属区县
        $yab003 = $_POST['yab003'];

        $funNo = 'HMHN001';    //交易编号
        $xml = "<input><chi037>".$chi037."</chi037><yab003>".$yab003."</yab003><chw017>01</chw017><fwbh>getPolicyInfo</fwbh></input>";
        $client = new \SoapClient(C('URL_API'));
        $result_list = $this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/HM0005/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        $res['code'] = 0;
        $res['message'] = '暂未查询到相关政策文件信息';
        if (isset($result_list['code']) && $result_list['code'] == "1") {
            if (count($result_list['output']) == 0) {
                $res['message'] = '暂未查询到相关政策文件信息';
                echo json_encode($res);exit();
            }
            $res['code'] = 1;
            $res['message'] = 'success';
            $res['item'] = $result_list['output'];
        }
        echo json_encode($res);
    }

    /**
     * 惠民惠农_按条件获取相关政策文件查询
     */
    function HM0006(){
        //政策文件主键
        $chi050 = $_POST['chi050'];

        $funNo = 'HMHN001';    //交易编号
        $xml = "<input><chi050>".$chi050."</chi050><chw017>01</chw017><fwbh>getPdf</fwbh></input>";
        $client = new \SoapClient(C('URL_API'));
        $result_list = $this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/HM0006/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        $res['code'] = 0;
        $res['message'] = 'his查询错误';
        if (isset($result_list['code']) && $result_list['code'] == "1") {
            if (count($result_list['output']) == 0) {
                $res['message'] = 'his查询数据无';
                echo json_encode($res);exit();
            }
            $res['code'] = 1;
            $res['message'] = 'success';
            $res['item'] = $result_list['output'];
        }
        echo json_encode($res);
    }

    /**
     * 惠民惠农_投诉举报
     */
    function HM0007(){
        //投诉类别
        $chb091 = $_POST['chb091'];
        //投诉标题
        $chb092 = $_POST['chb092'];
        //投诉人姓名
        $aac003 = $_POST['aac003'];
        //投诉人身份证号
        $aac002 = $_POST['aac002'];
        //投诉内容
        $chb093 = $_POST['chb093'];
        //投诉人电话
        $aae005 = $_POST['aae005'];
        //投诉人地址
        $aae006 = $_POST['aae006'];
        //图片原件
        $chb22c = $_POST['chb22c'];

        $funNo = 'HMHN001';    //交易编号
        $xml = "<input><chb091>".$chb091."</chb091><chb092>".$chb092."</chb092><aac003>".$aac003."</aac003><aac002>".$aac002."</aac002><chb093>".$chb093."</chb093><aae005>".$aae005."</aae005><aae006>".$aae006."</aae006><aae036>".date('Y/m/d',time())."</aae036><row><chb221>身份证正面.jpg</chb221><chb222>1</chb222><chb229></chb229><chb22c>".$chb22c."</chb22c></row><fwbh>saveComplaint</fwbh></input>";
        $client = new \SoapClient(C('URL_API'));
        $result_list = $this->Get_service_api($xml,$funNo,$client);

        $fileContent = '入参'.$xml.'+出参'.json_encode($result_list);
        $dir = "soapGetDate/" . date("Y-m-d") . "/HM0007/";
        $filename = date("H_i_s") . "_" . rand(10000, 99999);
        writeLog($dir, $filename, $fileContent);

        $res['code'] = 0;
        $res['message'] = 'his查询错误';
        if (isset($result_list['code']) && $result_list['code'] == "1") {
            if (count($result_list['output']) == 0) {
                $res['message'] = 'his查询数据无';
                echo json_encode($res);exit();
            }
            $res['code'] = 1;
            $res['message'] = 'success';
            $res['item'] = $result_list['output'];
        }
        echo json_encode($res);
    }
}
?>
